import os
import datetime
from rest_framework import permissions, filters, response, status
from rest_framework.decorators import action
from apps.api.testcase.models import TestCaseModel
from apps.api.testcase.serializers import TestCaseModelSerializer, RunTestCaseModelSerializer
from apps.api.interface.models import InterfaceModel
from apps.api.project.models import ProjectModel
from apps.basic.environment.models import EnvironmentModel
from base.settings import YML_FILE_PATH
from utils import viewsets, common


class TestCaseViewSet(viewsets.MyViewSets):
    queryset = TestCaseModel.objects.all()
    serializer_class = TestCaseModelSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['create_time']

    def retrieve(self, request, *args, **kwargs):
        result = super().retrieve(request, *args, **kwargs)
        result.data["data"]["project_id"] = InterfaceModel.objects.filter(id=result.data["data"]["interface_id"])\
            .filter(is_delete=0).first().project_id
        result.data["data"]["project"] = ProjectModel.objects.filter(id=result.data["data"]["project_id"])\
            .filter(is_delete=0).first().name
        return response.Response(result.data, status=status.HTTP_200_OK)

    def list(self, request, *args, **kwargs):
        result = super().list(request, *args, **kwargs)
        for item in result.data["data"]["results"]:
            item["project_id"] = InterfaceModel.objects.filter(id=item["interface_id"])\
                .filter(is_delete=0).first().project_id
            item["project"] = ProjectModel.objects.filter(id=item["project_id"]).filter(is_delete=0).first().name
        return response.Response(result.data, status=status.HTTP_200_OK)

    @action(methods=["POST"], detail=True)
    def run(self, request, *args, **kwargs):
        # 获取要运行的用例对象
        case_obj = self.get_object()
        super().create(request, *args, **kwargs)
        # 获取要运行的环境对象
        env = EnvironmentModel.objects.filter(id=request.data["env_id"]).filter(is_delete=0).first()
        # 创建时间戳文件夹
        stamp_path = os.path.join(YML_FILE_PATH, datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d%H%M%S"))
        os.makedirs(stamp_path)
        # 组装用例
        common.assemble_case(stamp_path, env, case_obj)
        # 运行用例
        return common.run_case(case_obj.name, stamp_path)

    def get_serializer_class(self):
        if self.action == "run":
            return RunTestCaseModelSerializer
        else:
            return self.serializer_class

    def perform_create(self, serializer):
        """当action等于run的时候，跳过创建"""
        if self.action == "run":
            pass
        else:
            serializer.save()
